package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ProjectName: changgou_parent
 * @Package: com.changgou.file.controller
 * @ClassName: FileController
 * @Author: Zhang SongYuan
 * @Date: 2020/3/26 19:54
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/download")
    public Result update(MultipartFile file) {

        try {
            //判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }
            //获取文件的完整名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("文件不存在");
            }
            //获取文件的扩展名称  abc.jpg   jpg
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取文件内容
            byte[] bytes = file.getBytes();
            //创建文件上传的封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, substring);
            //基于工具类进行文件上传,并接受返回参数  String[]
            String[] upload = FastDFSClient.upload(fastDFSFile);
            //封装返回结果
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "上传失败");
    }

    @DeleteMapping("/dele")
    public Result dele(String file_id) throws Exception {
        try {
            FastDFSClient.deleteFile1(file_id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件删除失败");
        }
        return new Result();
    }
}
